package com.mnsk.generator.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.mnsk.generator.common.datasource.DynamicDataSource;
import com.mnsk.generator.common.datasource.DynamicDataSourceUtil;
import com.mnsk.generator.common.utils.text.Convert;
import com.mnsk.generator.domain.SysDataSource;
import com.mnsk.generator.common.utils.DataSourceComposeUtils;
import com.mnsk.generator.common.aspectj.lang.enums.DataSourceType;
import com.mnsk.generator.config.properties.DruidProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * druid 配置多数据源
 *
 * @author admin
 * @date 2020-11-15 12:01:34
 */
@Configuration
public class DruidConfig {

    /**
     * 配置主数据源
     *
     * @param druidProperties 配置信息
     * @return 数据源
     */
    @Bean
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource masterDataSource(DruidProperties druidProperties) {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

    /**
     * 多数据源配置
     */
    @Primary
    @Bean(name = "dynamicDataSource")
    public DynamicDataSource dataSource(DataSource masterDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
        // 从数据库中直接读取配置信息
        JdbcTemplate jdbcTemplate = new JdbcTemplate(masterDataSource);
        List<SysDataSource> dsList = jdbcTemplate.query("select * from t_sys_data_source", new Object[]{},
                new BeanPropertyRowMapper<>(SysDataSource.class));
        if (dsList.size() > 0) {
            for (SysDataSource item : dsList) {
                DruidDataSource dds = DataSourceComposeUtils.composeDruidDataSource(item);
                // 将数据源添加到数据源集合（数据源变量 SLAVE + 数据源ID）
                targetDataSources.put(DataSourceType.SLAVE.name() + Convert.toStr(item.getId()), dds);
            }
        }
        DynamicDataSourceUtil.setTargetDataSources(targetDataSources);
        return new DynamicDataSource(masterDataSource, targetDataSources);
    }

}
